import React from 'react';
import {Spin, Card, Button, Row, Col, Form, Popconfirm, Message as msg, Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, FIXED_COLUMN_WIDTH, DATE_FORMAT, TABLE, DATETIME_FORMAT} from '../constants';
import {checkLaborType} from './constants';
import {formatDateTime, formatAmount, conventEnumValueToString} from '../utils';
import {addApplyReport, updateApplyReport, getDetail, getTechnologyActivitySimple} from './api';
import TextInput from 'Shared/components/TextInput';
import SearchSelect from 'Shared/components/SearchSelect';
import TechnologyActivityVehicleSelectPanel from './TechnologyActivityVehicleSelectPanel';
import TechnologyActivitySelectPanel from './TechnologyActivitySelectPanel';
import {laborType} from '../Enum';
import ImportPanel from './ImportPanel';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import WrappedDatePicker from '../common/WrappedDatePicker';
import {injectIntl, language, formatMessage} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

const laborTypeToList = laborType.toList(language);
const checkLaborTypeToList = checkLaborType.toList(language);
class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showTechnologyActivitySelectPanel: false,
        showTechnologyActivityVehicleSelectPanel: false,
        showImportPanel: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details,
                        });
                    else
                        this.setState({loading: false});
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const isValid = newOrUpdateOrderValidator(data, details);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const addCondition = {
            brandId: data.brandId,
            technologyActivityId: data.technologyActivityId,
            remark: data.remark,
            details: details.map(v => ({
                dealerId: v.dealerId,
                technologyActivityVehicleId: v.technologyActivityVehicleId,
                mileage: v.mileage,
                repairDate: v.repairDate,
                labourType: v.labourType,
            })),
        };
        const updateCondition = {
            remark: data.remark,
            rowVersion: data.rowVersion,
            details: details.map(v => ({
                dealerId: v.dealerId,
                technologyActivityVehicleId: v.technologyActivityVehicleId,
                mileage: v.mileage,
                repairDate: v.repairDate,
                labourType: v.labourType,
            })),
        };
        this.setState({loading: true});
        if(data.id)
            updateApplyReport(this.props.id, updateCondition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else
            addApplyReport(addCondition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickSearchTechnologyActivityBtn = () => {
        this.setState({
            showTechnologyActivitySelectPanel: true
        });
    }
    onCloseTechnologyActivitySelectPanel = () => {
        this.setState({showTechnologyActivitySelectPanel: false});
    }
    onSelectTechnologyActivity = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                technologyActivityId: records.id,
                technologyActivityCode: records.code,
                technologyActivityName: records.serviceName,
                startTime: records.startTime,
                endTime: records.endTime,
                causePartCode: records.causePartCode,
                causePartName: records.causePartName,
                checkLabor: records.checkLabor,
                checkChangeLabor: records.checkChangeLabor,
                checkChangeAssistLabor: records.checkChangeAssistLabor,
                checkLaborFee: records.checkLaborFee,
                checkChangeLaborFee: records.checkChangeLaborFee,
                checkChangeAssistLaborFee: records.checkChangeAssistLaborFee,
            }),
            hasOperat: true,
            showTechnologyActivitySelectPanel: false
        });
    }
    onSearchTechnologyActivity = value => {
        const {technologyActivityVehicleId} = this.state.data;
        return getTechnologyActivitySimple({
            filter: value,
            technologyActivityVehicleId
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    }
    labelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.serviceName}`;
        return '';
    }
    onDetailonChange = (value, name, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value ? value : ' ',
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onClickAddDetailBtn = () => {
        if(this.props.initEnumData.brands.length >= 1 && !this.state.data.brandId)
            return msg.warn(formatMessage({
                id: 'updatePanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.technologyActivityId)
            return msg.warn(formatMessage({
                id: 'updatePanel.message.technologyActivityId',
                defaultMessage: '请先选择技术升级'
            }));
        this.setState({
            showTechnologyActivityVehicleSelectPanel: !this.state.showTechnologyActivityVehicleSelectPanel
        });
    }
    onSelectTechnologyActivityVehicle = value => {
        const details = this.state.details;
        value.map(p => {
            const detail = this.state.details.find(d => d.id === p.id);
            if(!detail) {
                const detail = {
                    id: p.id,
                    vin: p.vin,
                    engineCode: p.engineCode,
                    saleDate: p.saleDate,
                    mileage: p.mileage,
                    labourType: p.labourType,
                    laborFee: p.laborFee,
                    materialFee: p.materialFee,
                    mgmtFee: p.mgmtFee,
                    assistantFee: p.assistantFee,
                };
                details.push(detail);
            }
            return p;
        });
        this.setState({
            showTechnologyActivityVehicleSelectPanel: false,
            hasOperat: true,
            details
        });
    }
    onSelectDealer = (value, id) => {
        const details = this.state.details;
        const tmp = details.map(p => {
            if(p.id === id)
                return Object.assign({}, p, {
                    dealerId: value.id,
                    dealerCode: value.code,
                    dealerName: value.name
                });
            return p;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
        });
    }
    onClickImportBtn = () => {
        this.setState({showImportPanel: true});
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onImportChange = records => {
        if(records.payload) {
            const importDetails = this.state.details || [];
            records.payload.content.forEach(r => {
                const index = importDetails.findIndex(v => v.id === r.id);
                if(index === -1)
                    importDetails.push({
                        id: r.id,
                        dealerId: r.dealerId,
                        dealerCode: r.dealerCode,
                        dealerName: r.dealerName,
                        vin: r.vin,
                        engineCode: r.engineCode,
                        saleDate: r.saleDate,
                        mileage: r.mileage,
                        laborFee: r.laborFee,
                        materialFee: r.materialFee,
                        mgmtFee: r.mgmtFee,
                        assistantFee: r.assistantFee,
                        totalFee: r.totalFee,
                    });
                else
                    importDetails.splice(index, 1, {
                        id: r.id,
                        dealerId: r.dealerId,
                        dealerCode: r.dealerCode,
                        dealerName: r.dealerName,
                        vin: r.vin,
                        engineCode: r.engineCode,
                        saleDate: r.saleDate,
                        mileage: r.mileage,
                        laborFee: r.laborFee,
                        materialFee: r.materialFee,
                        mgmtFee: r.mgmtFee,
                        assistantFee: r.assistantFee,
                        totalFee: r.totalFee,
                    });
            });
            this.setState({
                details: [...importDetails],
                hasOperat: true,
                showImportPanel: false,
            });
        }
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.id !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {data, details, isValidate, loading} = this.state;
        const {id} = this.props;
        const {brands = []} = this.props.initEnumData;
        if(brands.length === 1 && !id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        const technologyActivityInfo = data.technologyActivityId ? {
            id: data.technologyActivityId,
            code: data.technologyActivityCode,
            serviceName: data.technologyActivityName
        } : null;
        let laborFee = 0;
        let materialFee = 0;
        let mgmtFee = 0;
        let assistantFee = 0;
        let totalFee = 0;
        if(details)
            details.forEach(d => {
                laborFee += (d.laborFee || 0);
            });
        if(details)
            details.forEach(d => {
                materialFee += (d.materialFee || 0);
            });
        if(details)
            details.forEach(d => {
                mgmtFee += (d.mgmtFee || 0);
            });
        if(details)
            details.forEach(d => {
                assistantFee += (d.assistantFee || 0);
            });
        totalFee = laborFee + materialFee + mgmtFee + assistantFee;
        let type = 0;
        if(data.checkLabor > 0) {
            type = 1;
            laborFee = data.checkLaborFee;
        }
        if(data.checkLabor > 0 && data.checkChangeLabor > 0) {
            type = 2;
            laborFee = data.checkChangeLaborFee;
        }
        if(data.checkLabor > 0 && data.checkChangeLabor > 0 && data.checkChangeAssistLabor > 0) {
            type = 3;
            laborFee = data.checkChangeAssistLaborFee;
        }
        const columns = [{
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.dealerCode',
                defaultMessage: '经销商'
            })}</span>,
            dataIndex: 'dealerCode',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                const dealerInfo = record.dealerId ? {
                    id: record.dealerId,
                    code: record.dealerCode,
                    name: record.dealerName
                } : null;
                return (
                    <FormItem {...validate}>
                        <DealerSelectPanel
                            id={record.id}
                            value={dealerInfo}
                            onChange={value => this.onDetailonChange(value, 'dealerCode', record.id)}
                            onSelect={this.onSelectDealer} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.vin',
                defaultMessage: 'VIN'
            })}</span>,
            dataIndex: 'vin',
        }, {
            title: formatMessage({
                id: 'addPanel.column.engineCode',
                defaultMessage: '发动机号'
            }),
            dataIndex: 'engineCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.saleDate',
                defaultMessage: '实销日期'
            }),
            dataIndex: 'saleDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.mileage',
                defaultMessage: '行驶里程（KM）'
            })}</span>,
            dataIndex: 'mileage',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            id={record.id}
                            value={text}
                            onChange={value => this.onDetailonChange(value, 'mileage', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.repairDate',
                defaultMessage: '维修日期'
            })}</span>,
            dataIndex: 'repairDate',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedDatePicker
                            name={record.id}
                            value={text}
                            onChange={value => this.onDetailonChange(value, 'repairDate', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.labourType',
                defaultMessage: '工时类型'
            })}</span>,
            dataIndex: 'labourType',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        {type === 1 ? conventEnumValueToString(laborType, type)
                            : <WrappedSelect
                                allowClear
                                id={record.id}
                                options={type === 2 ? checkLaborTypeToList : laborTypeToList}
                                value={text}
                                onChange={value => this.onDetailonChange(value, 'labourType', record.id)} />}
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.laborFee',
                defaultMessage: '工时费'
            })}</span>,
            dataIndex: 'laborFee',
            render: () => formatAmount(laborFee)
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.materialFee',
                defaultMessage: '材料费'
            })}</span>,
            dataIndex: 'materialFee',
            render: text => formatAmount(text)
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.mgmtFee',
                defaultMessage: '管理费'
            })}</span>,
            dataIndex: 'mgmtFee',
            render: text => formatAmount(text)
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.assistantFee',
                defaultMessage: '辅料费'
            })}</span>,
            dataIndex: 'assistantFee',
            render: text => formatAmount(text)
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.totalFee',
                defaultMessage: '总金额'
            })}</span>,
            dataIndex: 'totalFee',
            render: (text, record) => formatAmount((record.laborFee || 0) +
                (record.materialFee || 0) + (record.mgmtFee || 0) + (record.assistantFee || 0))
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'addPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '技术升级索赔信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {id
                                            ? data.code : <span className="value-font">{formatMessage({
                                                id: 'addPanel.value.defalut',
                                                defaultMessage: '尚未生成'
                                            })}</span>}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        {id
                                            ? `(${data.brandCode})${data.brandName}` : <WrappedSelect
                                                name="brandId"
                                                value={data.brandId}
                                                options={brands}
                                                onChange={this.onChange}/>}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.technologyActivityId',
                                        defaultMessage: '技术升级'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.technologyActivityId ? 'error' : null} required>
                                        {id
                                            ? `(${data.technologyActivityCode})${data.technologyActivityName}` : <SearchSelect
                                                onSelect={this.onSelectTechnologyActivity}
                                                onSearch={this.onSearchTechnologyActivity}
                                                value={technologyActivityInfo}
                                                keyIndex="id"
                                                labelMap={this.labelMap}
                                                onClickSearchBtn={() => this.onClickSearchTechnologyActivityBtn()} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.startTime',
                                        defaultMessage: '开始时间'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.startTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.endTime',
                                        defaultMessage: '结束时间'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.endTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.causePartCode',
                                        defaultMessage: '主因件编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.causePartCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.causePartName',
                                        defaultMessage: '主因件名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.causePartName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.laborFee',
                                        defaultMessage: '工时费'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(laborFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.materialFee',
                                        defaultMessage: '材料费'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(materialFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.mgmtFee',
                                        defaultMessage: '管理费'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(mgmtFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.assistantFee',
                                        defaultMessage: '辅料费'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(assistantFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.totalFee',
                                        defaultMessage: '费用合计'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(totalFee)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            type="textarea"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'addPanel.operation.detail',
                            defaultMessage: '技术升级索赔清单'
                        })} extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickImportBtn}>
                                {formatMessage({
                                    id: 'updatePanel.operation.import',
                                    defaultMessage: '导入清单'
                                })}
                            </Button>
                            <Button
                                size="small"
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'addPanel.btn.add',
                                    defaultMessage: '增加清单'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showTechnologyActivitySelectPanel &&
                    <TechnologyActivitySelectPanel
                        selectKey={data.id}
                        onCancel={this.onCloseTechnologyActivitySelectPanel}
                        onSelect={this.onSelectTechnologyActivity} />
                }
                {
                    this.state.showTechnologyActivityVehicleSelectPanel && <TechnologyActivityVehicleSelectPanel
                        technologyActivityId={data.technologyActivityId}
                        selectKey={details.id}
                        onCancel={this.onClickAddDetailBtn}
                        onSelect={this.onSelectTechnologyActivityVehicle} />
                }
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        selectKey={details.id}
                        technologyActivityId={data.technologyActivityId}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
